<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索用户数据 -->
    <el-card class="box-card">
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" @keyup.enter.native="getUserList" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="addUserDialogVisible = true">主要按钮</el-button>
        </el-col>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="addUserClose">
          <el-form :model="addUserRuleForm" :rules="addUserRules" ref="addUserRuleForm" label-width="100px">
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="addUserRuleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="addUserRuleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserRuleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addUserRuleForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <!-- 数据 -->
      <el-table :data="userlist" style="width: 100%" stripe>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-row type="flex" justify="space-around">
              <!-- 编辑图标 -->
              <el-col :span="8">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserOpen(scope.row.id)"></el-button>
                <!-- 编辑用户对话框 -->
                <el-dialog title="编辑用户" :visible.sync="editUserDialogVisible" width="50%" @close="editUserClose">
                  <el-form :model="editUserRuleForm" :rules="addUserRules" ref="editUserRuleForm" label-width="100px">
                    <el-form-item label="用户名">
                      <el-input v-model="editUserRuleForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="editUserRuleForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                      <el-input v-model="editUserRuleForm.mobile"></el-input>
                    </el-form-item>
                  </el-form>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="editUserDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUser">确 定</el-button>
                  </span>
                </el-dialog>
              </el-col>
              <!-- 删除图标 -->
              <el-col :span="8">
                <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delUserconfirm(scope.row.id)">
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"></el-button>
                </el-popconfirm>
              </el-col>
              <!-- 分配角色图标 -->
              <el-col :span="8">
                <el-button type="info" icon="el-icon-setting" size="mini" @click="assignRoles(scope.row)"></el-button>
                <!-- 点击上面按钮打开的对话框 -->
                <el-dialog title="分配角色" :visible.sync="assignRolesDialogVisible" width="50%" @close="assignRolesClose">
                  <div>
                    <p>当前的用户:{{userInfo.username}}</p>
                    <p>当前的角色:{{userInfo.role_name}}</p>
                    <p>
                      分配新角色:
                      <el-select v-model="selectValue" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
                      </el-select>
                    </p>
                  </div>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="assignRolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="assignRolesSubmit">确 定</el-button>
                  </span>
                </el-dialog>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (!regEmail.test(value)) {
        callback(new Error("请输入合法的邮箱"));
      }
      callback();
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!regMobile.test(value)) {
        callback(new Error("请输入合法的手机号"));
      }
      callback();
    };

    return {
      queryInfo: { query: "", pagenum: 1, pagesize: 2 },
      userlist: [],
      total: 0,
      //以下直到下行注释之前均为添加用户对话框的数据
      addUserDialogVisible: false,
      addUserRuleForm: { username: "", password: "", email: "", mobile: "" },
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //以下直到下行注释之前均为编辑用户对话框的数据
      editUserDialogVisible: false,
      editUserRuleForm: { id: 0, username: "", email: "", mobile: "" },
      //以下直到下行注释之前均为分配角色对话框的数据
      assignRolesDialogVisible: false,
      userInfo: {}, //当前选择器中被选中的value当前用户的数据
      rolesList: [], //所有角色列表
      selectValue: "", //当前选择器中被选中的value
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$http
        .get("users", {
          params: this.queryInfo,
        })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("获取用户列表失败！");
          }
          this.userlist = res.data.data.users;
          this.total = res.data.data.total;
        });
    },
    // 分页下拉pageSize 改变时会触发
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newCurrent) {
      this.queryInfo.pagenum = newCurrent;
      this.getUserList();
    },
    // 监听 switch 开关状态的改变
    userStateChanged(data) {
      console.log(data);
      this.$http.put(`users/${data.id}/state/${data.mg_state}`).then((res) => {
        if (res.data.meta.status !== 200) {
          data.mg_state = !userinfo.mg_state;
          return this.$message.error("更新用户状态失败！");
        }
      });
    },
    test(a) {
      console.log(a);
    },
    // 关闭添加用户对话框，重置表单
    addUserClose() {
      this.$refs.addUserRuleForm.resetFields();
    },
    //添加用户
    addUser() {
      //预校验，如果为false则return出去
      this.$refs.addUserRuleForm.validate((valid) => {
        if (!valid) {
          this.$message.error("error submit!");
          return;
        }
        this.$http.post("users", this.addUserRuleForm).then((res) => {
          if (res.data.meta.status !== 201) {
            this.$message.error("添加用户失败！");
          } else {
            this.$message.success("添加用户成功！");
            this.addUserDialogVisible = false;
          }
        });
      });
    },
    //打开编辑用户
    editUserOpen(id) {
      this.editUserDialogVisible = true;
      this.$http.get(`users/${id}`).then((res) => {
        const data = res.data;
        this.editUserRuleForm.id = data.data.id;
        this.editUserRuleForm.username = data.data.username;
        this.editUserRuleForm.email = data.data.email;
        this.editUserRuleForm.mobile = data.data.mobile;
      });
    },
    // 关闭编辑用户对话框，重置表单
    editUserClose(a) {
      this.$refs.editUserRuleForm.resetFields();
    },
    // 编辑用户
    editUser() {
      //预校验，如果为false则return出去
      this.$refs.editUserRuleForm.validate((valid) => {
        if (!valid) {
          this.$message.error("error submit!");
          return;
        }
        this.$http
          .put(`users/${this.editUserRuleForm.id}`, {
            email: this.editUserRuleForm.email,
            mobile: this.editUserRuleForm.mobile,
          })
          .then((res) => {
            if (res.data.meta.status !== 200) {
              this.$message.error("修改失败！");
            } else {
              this.$message.success("修改成功！");
              this.editUserDialogVisible = false;
            }
          });
      });
    },
    // 确认删除用户
    delUserconfirm(id) {
      this.$http.delete(`users/${id}`).then((res) => {
        console.log(res);
        if (res.data.meta.status !== 200) {
          this.$message.error("删除失败");
        } else {
          this.getUserList();
          this.$message.success("删除成功");
        }
      });
    },
    // 分配角色
    assignRoles(row) {
      // 把当前用户信息存储在data中供对话框使用
      this.userInfo = row;
      // 获取所有角色
      this.$http.get("roles").then((res) => {
        this.rolesList = res.data.data;
      });
      this.assignRolesDialogVisible = true;
    },
    // 提交分配角色
    assignRolesSubmit() {
      // 判断选择器有没有选中(即selectValue中有没有数据)
      if (!this.selectValue) {
        return this.$message.error("请选择分配一个新角色");
      } else {
        this.$http
          .put(`users/${this.userInfo.id}/role`, { rid: this.selectValue })
          .then((res) => {
            console.log(res);
            this.getUserList();
            this.assignRolesDialogVisible = false;
          });
      }
    },
    // 关闭分配角色对话框
    assignRolesClose() {
      this.selectValue = ""; //清空之前选择器选择后存储的数据
      this.userInfo = {}; //清空当前用户数据
    },
  },
};
</script>

<style scoped>
</style>